package com.wzy.springbootdemo.service;

import com.wzy.springbootdemo.mapper.UserMapper;
import com.wzy.springbootdemo.model.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public List<User> getUsers() {
        //字符串序列化器，增强key的可读性
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        //查询缓存
        List<User> userList = (List<User>) redisTemplate.opsForValue().get("users");

        //如果缓存里没有，则去数据库查，并放入缓存
        if (userList == null){
            //解决高并发缓存穿透
            synchronized (this){
                //查询缓存
                userList = (List<User>) redisTemplate.opsForValue().get("users");
                if (userList == null){
                    userList = userMapper.getUserListByMap();
                    System.out.println("查询数据库.............");
                    if (userList != null)
                        redisTemplate.opsForValue().set("users",userList);
                } else {
                    System.out.println("查询缓存.............");
                }
            }

        } else {
            System.out.println("查询缓存.............");
        }
        return userList;
    }

    @Transactional
    @Override
    public Integer updateUser(User user) {
        int result = userMapper.updateUser(user);
        System.out.println(result);
        int n = 1/0;
        return result;
    }
}
